from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from datetime import datetime
import time
import pytest


from zother.td_api import get_toplist,get_alarlist,get_site,get_userinfo


service = Service(executable_path=r'D:\pulg\webdriver\chromedriver-win64\chromedriver.exe')
wd = webdriver.Chrome(service=service)
wd.implicitly_wait(2)
# 打开网页
wd.get("http://hxzhan.rtcloud.com:32111/sso/?return_url=http://hxzhan.rtcloud.com:32111/temp/monitor#/login")
wd.maximize_window()
wait = WebDriverWait(wd,10,poll_frequency=0.5)
#时间戳转换为时间
def timestran(timestamp):
    seconds_timestamp = timestamp / 1000.0
    date_time_obj = datetime.fromtimestamp(seconds_timestamp)
    return str(date_time_obj).split('.')[0]

#登录函数
def login(name,password):
    wd.find_element(By.NAME,'username').send_keys(name)
    wd.find_element(By.NAME,'password').send_keys(password)
    wd.find_element(By.XPATH,'//span[text()="登录"]').click()
def clear():
    wd.find_element(By.NAME,'username').clear()
    wd.find_element(By.NAME,'password').clear()  


# 用户登录
@pytest.mark.u1
def test_login ():
    #账号密码为空登录
    login('','')
    wait.until(EC.visibility_of_all_elements_located((By.CLASS_NAME,'el-form-item__error')))
    assert wd.find_elements(By.CLASS_NAME,'el-form-item__error')[0].text == "请输入用户名"
    assert wd.find_elements(By.CLASS_NAME,'el-form-item__error')[1].text == "请输入密码"
    #账号错误登录
    clear()
    login('xiaoqing2','a143384566!')
    wait.until(EC.visibility_of_all_elements_located((By.CLASS_NAME,'el-message__content')))
    assert wd.find_element(By.CLASS_NAME,'el-message__content').text == "用户名或密码错误"
    #密码错误登录
    clear()
    login('xiaoqing2','a143384566!')
    wait.until(EC.visibility_of_all_elements_located((By.CLASS_NAME,'el-message__content')))
    assert wd.find_element(By.CLASS_NAME,'el-message__content').text == "用户名或密码错误"
    #账号密码正确登录
    clear()
    login('xiaoqing','a143384566!')
    wait.until(EC.visibility_of_element_located((By.XPATH,'//div[@class="ele-admin-logo"]/span')))
    assert wd.find_element(By.XPATH,'//div[@class="ele-admin-logo"]/span').text == '温度监测'
#个人中心
@pytest.mark.u1
def test_centerperson():
    ActionChains(wd).move_to_element(wd.find_element(By.XPATH,'//div[@class="ele-admin-header-tool-item"]')).perform()
    ActionChains(wd).click(wd.find_element(By.XPATH,'//div[text()="个人中心"]')).perform()

    page_userinfolist= []
    api_userinfolist = []
    key_userinfolist = ['real_name','id_card','gender','phone','email']
    # ,'ctrl_role_list','data_role_list'
    elms = wait.until(EC.visibility_of_all_elements_located((By.XPATH,'//div[@class="ant-form-item-control-input"]/div')))
    #获取页面用户信息
    for elm in elms:
        page_userinfolist.append(elm.text)
    elms = wait.until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR,'.ant-tag.ant-tag-blue')))
    for elm in elms:
        page_userinfolist.append(elm.text)
    #获取接口用户信息
    print(get_userinfo())
    for userinfo in get_userinfo():
        for key in key_userinfolist:
            print(userinfo[key])











    # print(page_userinfolist)

#首页菜单导航跳转
def test_pagejump():
    #首页跳转
    wd.find_element(By.XPATH,'//span[text()="温度监测"]').click()
    assert wd.find_element(By.XPATH,'//div[@class="ele-admin-logo"]/span').text == '温度监测'
    #首页菜单导航跳转
    wait.until(EC.visibility_of_element_located((By.XPATH,'//div[@class="ele-admin-logo"]/span')))
    assert wd.find_element(By.XPATH,'//div[@class="ele-admin-logo"]/span').text == '温度监测'
    titilelist = ['系统首页','站点统计','实时监测','历史数据','告警查询','运行报告']
    childnavlist = ['告警设置','短信告警设置','数据设置','用户列表','操作角色管理','数据角色管理','操作日志',]
    titles = wait.until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR,'.ant-menu-overflow-item.ant-menu-item')))
    for index,title in enumerate(titles):
        title.click()
        assert title.text == titilelist[index]
        time.sleep(0.1)
    #首页子菜单跳转    
    system_menu = wd.find_element(By.XPATH, '//span[text()="系统管理"]')
    ActionChains(wd).move_to_element(system_menu).perform()
    elms = wait.until(EC.presence_of_all_elements_located((By.XPATH, '//span[@class="ant-menu-title-content"]/span')))
    for index, elm in enumerate(elms):
        if index > 7:
            ActionChains(wd).move_to_element(wd.find_element(By.XPATH, '//span[text()="系统管理"]')).perform()
            ActionChains(wd).move_to_element(elm).click().perform()
            assert elm.text == childnavlist[index-8]
    wd.find_element(By.XPATH,'//span[text()="温度监测"]').click()

#系统首页
def test_homepage():
    #顶部数据
    page_toplist = []
    api_toplist = []
    key_toplist = ['app_scen_count','gateway_count','device_count','alarm_device_count','app_scen_city_count','gateway_online_count',
            'gateway_offline_count','device_online_count','device_offline_count','alarm_device_yesterday']
    elms_top = wait.until(EC.visibility_of_all_elements_located((By.CLASS_NAME,'analysis-chart-card-num')))
    ##获取页面顶部数据
    for elm in elms_top:
        page_toplist.append(elm.text)
    elms_bt = wait.until(EC.visibility_of_all_elements_located((By.CLASS_NAME,'analysis-trend-text')))
    ##获取接口顶部数据
    for index,elm in enumerate(elms_bt):
        if index == 0:
            page_toplist.append(elm.text.replace('在','|').replace('个','|').split('|')[1])
        elif index == 1 or index == 2:
            page_toplist.append(elm.text.replace('，',' ').split(' ')[0])
            page_toplist.append(elm.text.replace('，',' ').split(' ')[2])
        else:
            page_toplist.append(elm.text.split(' ')[1])
    for key in key_toplist:
        api_toplist.append(str(get_toplist()[key]))
    ##验证页面顶部数据与API接口数据一致
    assert page_toplist == api_toplist
    #告警数据显示
    page_alarlist = []
    api_alarlist = []
    key_alarlist = ['alarm_at','device_name','app_scen_name','desc','level','return_status']
    levellist = []
    alars = wait.until(EC.visibility_of_all_elements_located((By.CLASS_NAME,'ant-table-row')))
    for alar_tr in alars:
        for index,alar_td in enumerate(alar_tr.find_elements(By.CLASS_NAME,'ant-table-cell')):
            if index == 0:
                page_alarlist.append(alar_td.text)
            else:
                page_alarlist.append(alar_td.find_element(By.XPATH,'./span').text)
    for alar in get_alarlist():
        for key in key_alarlist:
            if key == 'alarm_at':
                api_alarlist.append(timestran(alar[key]))
            elif key == 'level':
                if alar[key] == 1:
                    api_alarlist.append('预警')
                elif alar[key] == 2:
                    api_alarlist.append('一般')
            elif key == 'return_status':
                if alar[key] == 2:
                    api_alarlist.append('未复归')
                elif alar[key] == 1:
                    api_alarlist.append('已复归')
            else:
                api_alarlist.append(alar[key])   
    ##验证页面告警列表和接口告警列表
    assert page_alarlist == api_alarlist
    ###告警分类统计表暂时无法判定#########
    #站点概览统计全部、在线、离线等数量
    page_sitenumber = []
    page_sitelist = []
    api_sitenumber = []
    api_sitelist = []
    key_sitenumber = ['total','online','offline','part_online']
    key_sitelist = ['app_scen_name','gateway_online_status','top_region_name','child_device_count','alarm_device_count','highest_temp','lowest_temp']
    ##获取页面站点数量
    sitenumber = wait.until(EC.visibility_of_all_elements_located((By.XPATH,'//label//span[2]')))
    for site in sitenumber:
        page_sitenumber.append(site.text.split('(')[1].split(')')[0])
    ##获取接口站点数量
    for key in key_sitenumber:
        api_sitenumber.append(str(get_site('number', 0)[key]))
    ##验证页面站点数量和接口站点数量
    assert page_sitenumber == api_sitenumber
    #站点详情
    #获取页面所有站点数据
    all_sitebt = wait.until(EC.visibility_of_all_elements_located((By.XPATH,'//label')))
    for index,sitebt in enumerate(all_sitebt):
        sitebt.click()
        if api_sitenumber[index] == '0':
            assert wd.find_element(By.CLASS_NAME,'ant-empty-description').text == '暂无数据'
        else:
            sites = wait.until(EC.visibility_of_all_elements_located((By.XPATH,'//div[@class="ant-card-body"]/div[@class="ant-row"]/div')))
            for site in sites:
                page_sitelist.append(site.find_element(By.XPATH,'.//b').text)
                page_sitelist.append(site.find_element(By.XPATH,'.//div/span[1]').text)
                page_sitelist.append(site.find_element(By.XPATH,'.//div[@class="address"]').text)
                page_sitelist.append(site.find_element(By.XPATH,'.//div[@class="info-item"][1]/div[1]').text)
                page_sitelist.append(site.find_element(By.XPATH,'.//div[@class="info-item"][2]/div[1]').text)
                page_sitelist.append(site.find_element(By.XPATH,'.//div[@class="info-item"][3]/div[1]').text)
                page_sitelist.append(site.find_element(By.XPATH,'.//div[@class="info-item"][4]/div[1]').text)
    #获取接口所有站点数据
    for i in range(0,4):
        for site in get_site('site',i):
            for key in key_sitelist:
                if key == 'gateway_online_status':
                    if site[key] == 1:
                        api_sitelist.append('网关状态：在线')
                    elif site[key] == 2:
                        api_sitelist.append('网关状态：离线')
                    elif site[key] == 3:
                        api_sitelist.append('网关状态：部分离线')
                else:
                    api_sitelist.append(str(site[key]))
    assert page_sitelist == api_sitelist
    ###底部数据统计,滚动比较麻烦########

